package org.amos.xss.core;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.amos.xss.cleaner.XssCleaner;
import org.amos.xss.properties.XssProperties;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @desc: Xss 过滤器
 * @author: liubt
 * @date: 2020-12-15 13:17
 **/
@RequiredArgsConstructor
public class XssFilter extends OncePerRequestFilter {

    /**
     * Xss 防注入配置
     */
    private final XssProperties xssProperties;

    private final XssCleaner xssCleaner;

    /**
     * AntPath规则匹配器
     */
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        filterChain.doFilter(new XssRequestWrapper(request, xssCleaner), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        // 关闭直接跳过
        if (!xssProperties.isEnabled()) {
            return true;
        }

        // 请求方法检查
        if (!StrUtil.equalsAnyIgnoreCase(request.getMethod(),
                xssProperties.getIncludeHttpMethods().toArray(new String[]{}))) {
            return true;
        }

        // 请求路径检查
        String requestUri = request.getRequestURI();
        // 此路径是否不需要处理
        for (String exclude : xssProperties.getExcludePaths()) {
            if (ANT_PATH_MATCHER.match(exclude, requestUri)) {
                return true;
            }
        }

        return false;
    }

}
